#include "widget.h"
#include "ui_widget.h"


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
//    //安装事件过滤器
//    ui->textEdit->installEventFilter(this);

    //虽然上面这行代码进行widget和ui窗口关联，但是如果发生窗口大小改变时，里面布局不会改变
    //通过下面这行代码进行显示说明，让窗口变化时，布局及其子控件随之调整
    this->setLayout(ui->verticalLayout);
    ui->widgetBtnL->setLayout(ui->PCLayout);
    ui->widgetBtnH->setLayout(ui->HLayout);

    //快捷键事件
    QShortcut *shortcutOpen = new QShortcut(QKeySequence(tr("Ctrl+O", "File|Open")),this);
    QShortcut *shortcutSave = new QShortcut(QKeySequence(tr("Ctrl+S", "File|Save")),this);
    QShortcut *shortcutZoomIn = new QShortcut(QKeySequence(tr("Ctrl+Shift+=", "File|ZoomIn")),this);
    QShortcut *shortcutZoomOut = new QShortcut(QKeySequence(tr("Ctrl+Shift+-", "File|ZoomOut")),this);
    QObject::connect(shortcutOpen, &QShortcut::activated, [=](){
        on_btnopen_clicked();
    });
    QObject::connect(shortcutSave, &QShortcut::activated, [=](){
        on_btnsave_clicked();
    });
    QObject::connect(shortcutZoomIn, &QShortcut::activated, [=](){
        myZoomIn();
    });
    QObject::connect(shortcutZoomOut, &QShortcut::activated, [=](){
        myZoomOut();
    });
    //按键事件
    QObject::connect(ui->btnOpen, SIGNAL(clicked()), this, SLOT(on_btnopen_clicked()));
    QObject::connect(ui->btnSave, SIGNAL(clicked()), this, SLOT(on_btnsave_clicked()));
    QObject::connect(ui->btnClose, SIGNAL(clicked()), this, SLOT(on_btnclose_clicked()));

    //编码事件
    QObject::connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onCurrentIndexChanged(int)));

    //行列号事件 cursorPositionChanged()
    QObject::connect(ui->textEdit, SIGNAL(cursorPositionChanged()), this, SLOT(oncursorPositionChanged()));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::myZoomIn()
{
    //获得Textedit当前字体信息
    QFont font = ui->textEdit->font();
    //获得字体大小
    int fontsize = font.pointSize();
    if(fontsize == -1)  return;
    //改变字体大小
    int newfontsize = fontsize + 1;
    font.setPointSize(newfontsize);
    ui->textEdit->setFont(font);
}

void Widget::myZoomOut()
{
    //获得Textedit当前字体信息
    QFont font = ui->textEdit->font();
    //获得字体大小
    int fontsize = font.pointSize();
    if(fontsize == -1)  return;
    //改变字体大小
    int newfontsize = fontsize - 1;
    font.setPointSize(newfontsize);
    ui->textEdit->setFont(font);
}

//bool Widget::eventFilter(QObject *obj, QEvent *ev)
//{
//    //判断滚轮和ctrl同时发生
//    if(ev->type() == QEvent::Wheel){
//        if(QGuiApplication::keyboardModifiers() == Qt::ShiftModifier){
//            //判断是滚轮向上还是向下
//            QWheelEvent *wheelevent = (QWheelEvent *)ev;
//            if(wheelevent->angleDelta().y() > 0){
//                myZoomIn();
//            }else if(wheelevent->angleDelta().y() < 0){
//                myZoomOut();
//            }
//            return true;
//        }
//        return false;
//    }
//}

void Widget::on_btnopen_clicked()
{
    //弹出对话框
    QString fileName = QFileDialog::getOpenFileName(this,
                                                    tr("Open File"),
                                                    "D:/Dock",
                                                    tr("Text Files (*.txt)"));
    //清除上一个缓存
    ui->textEdit->clear();
    //打开文件
    file.setFileName(fileName);
    if (!file.open(QIODevice::ReadWrite | QIODevice::Text)){
        qDebug() << "open failed";
        return;
    }
    //显示打开了哪个文件
    this->setWindowTitle(fileName + " - 小陈note");
    //读取文件
    QTextStream in(&file);
    //编码设置
    in.setCodec(ui->comboBox->currentText().toStdString().c_str());
    //显示
    while (!in.atEnd()) {
        QString line = in.readLine();
        ui->textEdit->append(line);
    }
}

void Widget::on_btnsave_clicked()
{
    //如果文件没打开则显示保存串口
    if(!file.isOpen()){
        //弹出对话框
        QString fileName = QFileDialog::getSaveFileName(this,
                                                        tr("Save File"),
                                                        "D:/Dock",
                                                        tr("Text (*.txt *.doc)"));
        // 检查用户是否取消保存
        if(fileName.isEmpty()) return;
        //打开文件
        file.setFileName(fileName);
        if (!file.open(QIODevice::ReadWrite | QIODevice::Text)){
            qDebug() << "open failed";
            return;
        }
        //显示打开了哪个文件
        this->setWindowTitle(fileName + " - 小陈note");
        //写入文件
        QTextStream out(&file);
        //编码设置
        out.setCodec(ui->comboBox->currentText().toStdString().c_str());
        //写入
        out << ui->textEdit->toPlainText();
        out.flush();
    }
    // 重置文件指针并清空内容
    file.resize(0);
    //写入文件
    QTextStream out(&file);
    //编码设置
    out.setCodec(ui->comboBox->currentText().toStdString().c_str());
    //写入
    out << ui->textEdit->toPlainText();
    out.flush();
    // 只有确保保存成功后才显示弹窗
    QMessageBox::information(this, tr("保存"), tr("文件已保存！"));
}

void Widget::on_btnclose_clicked()
{
    int ret = QMessageBox::warning(this, tr("小陈note警告"),
                                   tr("记事本即将被修改\n"
                                      "请问是否保存?"),
                                   QMessageBox::Save | QMessageBox::Discard
                                   | QMessageBox::Cancel,
                                   QMessageBox::Save);
    switch (ret) {
    case QMessageBox::Save:
        // Save was clicked
        on_btnsave_clicked();
        //关闭
        ui->textEdit->clear();
        if(file.isOpen()){
            file.close();
            this->setWindowTitle("小陈note");
        }
        break;
    case QMessageBox::Discard:
        // Don't Save was clicked
        ui->textEdit->clear();
        if(file.isOpen()){
            file.close();
            this->setWindowTitle("小陈note");
        }
        break;
    case QMessageBox::Cancel:
        // Cancel was clicked
        break;
    default:
        // should never be reached
        break;
    }
}

void Widget::onCurrentIndexChanged(int index)
{
    //清空
    ui->textEdit->clear();
    //判断文件是否打开
    if(file.isOpen()){
        //是：进行修改编码并且显示
        QTextStream in(&file);
        in.setCodec(ui->comboBox->currentText().toStdString().c_str());
        //光标回到开头
        file.seek(0);
        //显示
        while (!in.atEnd()) {
            QString line = in.readLine();
            ui->textEdit->append(line);
        }
    }
}

void Widget::oncursorPositionChanged()
{
    //获取当前光标位置
    QTextCursor cursor = ui->textEdit->textCursor();
    QString blocknum = QString::number(cursor.blockNumber() + 1);
    QString columnnum = QString::number(cursor.columnNumber() + 1);
    //显示
    const QString mes = "行:" + blocknum + "  " + "列:" + columnnum;
    ui->labelPosition->setText(mes);
    //设置当前行高亮
    QList<QTextEdit::ExtraSelection> extraSelection;
    QTextEdit::ExtraSelection ext;
    //知道当前行
    ext.cursor = cursor;
    //颜色(极浅的冷调绿色)
    QColor qClolor(245,255,250);
    ext.format.setBackground(qClolor);
    //选择全行
    ext.format.setProperty(QTextFormat::FullWidthSelection, true);
    //加入容器
    extraSelection.append(ext);
    //设置
    ui->textEdit->setExtraSelections(extraSelection);
}

